import React from 'react';
import { connect } from 'react-redux';
import { fetchDetail, postVote, postComment, postSurvey, initArticle } from '../actions/detail';
import Article from '../components/article';
import Message from 'antd/lib/message';
import ReactDom from 'react-dom';

class ArticlePage extends React.Component{
    constructor(props) {
        super(props);
    }

    componentDidMount(){
        this.props.fetchDetail(this.props.params.articleId);
    }

    componentWillUnmount() {
        this.props.initArticle();
    }
    handlePostVote(articleId){
        this.props.postVote(articleId, function(flg) {
            if (flg == 0) {
                Message.success('操作成功');
            }
        });
    }

    handlePostComment(comment){
        if(comment !== undefined && comment.length > 0) {
            if (comment.length > 400) {
                return Message.error('内容不要大于400个字！');
            } else {
                this.props.postComment(this.props.article.Id, comment, function(flg) {
                if (flg == 0) {
                    Message.success('管理员会尽快审核留言');
                }
            });
            }
        } else {
            Message.error('内容为空');
        }
    }

    handlePostSurvey(answer){
        this.props.postSurvey(this.props.article.Id, answer, function(flg) {
            if (flg == 0) {
                Message.success('操作成功');
            }
        });
    }

    componentDidUpdate() {
        let articleImgs = document.querySelectorAll("#articlephotos slider-slide");
        let articleList = document.querySelectorAll("#articlephotos slider-list");
        if (this.props.params.comment) {
            let comments = document.querySelector(".comment-container");
            // if (comments) 
            //     comments.scrollIntoView();
        }
    }

    render(){
        if(this.props.article == undefined && this.props.article == null){
            return(<div>Loading</div>)
        }else{
            return(
                <Article 
                    article={this.props.article} 
                    vote={this.props.vote} 
                    comments={this.props.comments} 
                    survey={this.props.survey}
                    surveyResult={this.props.surveyResult}
                    handlePostVote={this.handlePostVote.bind(this)} 
                    handlePostComment={this.handlePostComment.bind(this)}
                    handlePostSurvey={this.handlePostSurvey.bind(this)} 
                    redirectUrl={this.props.redirectUrl}/>
            );
        }
    }
}

function mapStateToProps(state){
    return { 
        article: state.detail.article,
        vote: state.detail.vote,
        comments: state.detail.comments,
        survey: state.detail.survey,
        surveyResult: state.detail.surveyResult,
        redirectUrl: state.detail.loginUrl
    };
}

export default connect(mapStateToProps, { fetchDetail, postVote, postComment, postSurvey, initArticle })(ArticlePage);